<!--
 * @Description: Description
 * @Author: Kerwin
 * @Date: 2025-11-25 10:24:22
 * @LastEditTime: 2025-11-25 10:24:23
 * @LastEditors:  Please set LastEditors
-->
<!--
 * @Description: 花了还有结算页面
 * @Author: Kerwin
 * @Date: 2025-05-26 14:46:49
 * @LastEditTime: 2025-11-12 13:36:47
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="physicalShopCheck">
    <u-navbar
      back-text=""
      :title="'店铺付款'"
      :title-bold="true"
      :is-back="!enterByStoreQrcode"
      v-if="!isWeChatBrowser && !isAlipayClient"
      color="#333"
    ></u-navbar>
    <!-- 头部 -->
    <view class="topTitLe">
      <view class="leftTitle">
        <view style="font-weight: 700; font-size: 32rpx; margin-bottom: 20rpx"
          >消费总金额</view
        >
        <view style="color: #999">请询问金额后提交</view>
      </view>
      <view class="rightTitle">
        <u-image width="180rpx" height="150rpx" :src="moneyIcon"></u-image>
      </view>
    </view>
    <!-- 商户信息 -->
    <view class="shopBox">
      <text class="name"
        ><u-icon
          size="40"
          style="vertical-align: middle"
          :name="shopIcon1"
        ></u-icon>
        {{ info.name }}</text
      >
      <view class="inptBox">
        <u-input
          v-model="money"
          v-input-decimal
          type="digit"
          inputmode="decimal"
          focus
          pattern="number"
          placeholder="¥ 0.00"
          input-align="center"
          :custom-style="{
            fontSize: '52rpx'
            // fontWeight: '800'
          }"
          :disabled="inptDisabled"
        />
        <text class="unit">(元)</text>
      </view>
      <view class="yt-list-cell shape2"  >
        <view class="cell-tit">
          抵用券抵扣：<text class="red"
            >（本次最多使用{{ scoreMax }}积分，可抵扣{{ scoreMax }}元）</text
          ></view
        >
        <view class="cell-tip">
          <view class="wallet"> 抵用券剩余：{{ userScore }}</view>
          <!-- <u-number-box :disabled="!userScore" v-model="score_consumption" :max="scoreMax" :min="0"></u-number-box> -->
          <view class="right" style="width: 250rpx">
            <!-- <u-input class="inputBox" :disabled="!userScore && userScore < 0" v-input-decimal placeholder="请输入抵扣积分"
              type="digit" v-model="score_consumption" @blur="onScoreChange" :border="true" /> -->

            <van-stepper
              :min="0"
              :max="scoreMax"
              v-model="score_consumption"
              @blur="onScoreChange"
              step="0.1"
              :decimal-length="1"
            />
          </view>
        </view>
        <!-- <view class="hjfScore"> 绿色积分剩余：{{ hjfUserScor }}</view> -->
      </view>

      <view
        class="radioBox"
        v-if="info.shopMoneyRules && info.shopMoneyRules.length > 1"
      >
        <u-radio-group
          v-model="moneyRuleId"
          @change="radioGroupChange"
          :wrap="true"
        >
          <u-radio
            v-for="(item, index) in info.shopMoneyRules"
            :key="index"
            :name="item.moneyRuleId"
          >
            {{ item.userMoneyRuleName }}
          </u-radio>
        </u-radio-group>
      </view>
      <!-- <u-form-item label-width="auto" label-position="top" :border-bottom="false" label="付款留言：">
        <u-input style="background-color: #f7f5f5; " :height="200" :border="true" type="textarea"
          v-model="orderData.remark" />
      </u-form-item> -->
    </view>
    <!-- 结算 -->
    <u-button class="hy-btn" type="primary" ripple @click="toPayment">
      确认付款
    </u-button>
    <!-- <view class="hy-link" v-if='bindPhone'  @click="toBindPhone">
      绑定手机号
 
    </view> -->

    <!-- #ifdef H5 -->
    <!-- <hyDownloadTips /> -->
    <!-- #endif -->
  </view>
</template>
<script setup lang="ts">
import { computed, reactive, ref, watch, nextTick } from 'vue'
import { onLoad, onShow, onReady } from '@dcloudio/uni-app'
//存储
import { storeToRefs } from 'pinia'
import { useConfigStore, useUserStore } from '@/store'
//api
import { enumAll, moneyApi, orderApi, productApi } from '@/api'
//  组件
import hyDownloadTips from '@/components/hy-download-tips/index.vue'
//工具
import { generateAlipayAuthUrl } from '@/utils/common'
import { Decimal } from 'decimal.js'
import debounce from 'lodash/debounce'
//图片
import moneyIcon from '@/static/hlhy/money2.png'
import shopIcon1 from '@/static/hlhy/shopIcon1.png'

//初始数据
const configStore = useConfigStore()
const userStore = useUserStore()
const { enterByStoreQrcode, isWeChatBrowser, isAlipayClient } =
  storeToRefs(configStore)
const { accessToken, useShareCode } = storeToRefs(userStore)
const info = reactive({
  name: '',
  shopId: '',
  shopMoneyRules: []
})
const money = ref()
const orderData = ref<any>({
  remark: ''
})
const productSku = ref()
const flqScore = ref()
const moneyRuleId = ref(null)
const userInfo = userStore.userInfo
const bindPhone = ref(false) //绑定手机号状态
const isHjfShop = ref(false) // 是否花积分
const isflqShop = ref(false) // 是否复来券
const score_consumption = ref(0)
const userScore = ref(0) // 用户积分余额
const hjfUserScor = ref(0) //花积分的积余额
const maxUserScor = ref(0) //固定积分上限
let _userScore = 0
// 是否白名单用户
const whiteList = ref(0)

// 创建订单
async function creatOrder() {
  console.log('提交的订单信息', orderData.value)
  try {
    const { data } = await orderApi.orderAdd(orderData.value)
    console.log('订单创建成功==>', data)
    if (data) {
      console.log(
        '跳转==>',
        `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}`
      )
      location.href = `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}`
    }
  } catch (err) {
    console.log(err)
  }
  uni.hideLoading()
}

const onScoreChange = (e: number) => {
  console.log(e, '支付的积分')
}

// 创建防抖版本的 creatOrder 函数，500 毫秒内只执行一次
const debouncedCreatOrder = debounce(creatOrder, 500)

async function toPayment() {
  if (!money.value) {
    uni.showToast({
      icon: 'none',
      title: '请输入支付金额'
    })
    return
  }
  if (money.value <= 0) {
    uni.showToast({
      icon: 'none',
      title: '最低金额需大于0元'
    })
    return
  }
  if (score_consumption.value > scoreMax.value) {
    uni.showToast({
      icon: 'none',
      title: '最多只能抵扣' + scoreMax.value + '元'
    })
    return
  }

  uni.showLoading({ title: '', mask: true })
  try {
    await getShopSku()
    // 卖手推荐的门店，卖手获得收益
    // 2023/9/11 扫店铺付款码进入无shareCode则不携带
    if (uni.getStorageSync('shareCode') && useShareCode.value) {
      orderData.value.orderProductSkus[0].externalData = {
        userShareCode: uni.getStorageSync('shareCode')
      }
    }
    // 调用防抖函数
    debouncedCreatOrder()
  } catch (err) {
    uni.hideLoading()
  }
}

//获取商铺skuss
const getShopSku = async () => {
  const { data } = await productApi.getShopProductSkuList({
    detail: false,
    dynamicPrice: true,
    shopId: info.shopId
  })
  if (data.records) {
    productSku.value = data.records[0]
    orderData.value.orderProductSkus = [
      {
        count: 1,
        money: money.value,
        shopProductSkuId: productSku.value.id,
        moneyRuleId: moneyRuleId.value,
        dynamicPric: true
      }
    ]
    if (score_consumption.value) {
      orderData.value.scoreMoney = score_consumption.value
    }
  }
}

async function getScore(walletRuleId: any) {
  const { data } = await moneyApi.walletInfo({
    walletRuleId
  })
  if (walletRuleId == 2013) {
    console.log('积分', data)
    hjfUserScor.value = Math.floor(data.money * 100) / 100
  } else {
    userScore.value = Math.floor(data.money * 10) / 10
    maxUserScor.value = Math.floor(data.money * 10) / 10
    _userScore = Math.floor(data.money * 10) / 10
  }
}

// #region ***************** 查询让利规则 *************************/
const getDeductionRate = (moneyRuleId: any) => {
  // 检查是否属于 25% 规则组
  if (enumAll.MoneyRuleGroups.GROUP_25.ruleIds.includes(moneyRuleId)) {
    return enumAll.MoneyRuleGroups.GROUP_25.rate // 0.25
  }

  // 检查是否属于 37.5% 规则组
  if (enumAll.MoneyRuleGroups.GROUP_375.ruleIds.includes(moneyRuleId)) {
    return enumAll.MoneyRuleGroups.GROUP_375.rate // 0.375
  }

  // 默认返回 0 或其他默认值
  return 0.5
}

// #endregion

const scoreMax = computed(() => {
  if (!orderData) return 0
  if (money.value) {
    let _money = 0
    if (isHjfShop.value && whiteList.value) {
      //白名单的店铺抵扣50%
      _money = money.value * 0.5
    } else if (isHjfShop.value && !whiteList.value) {
      //8-11 只能抵扣25% ,12-15   抵扣 37.5%
      const rate = getDeductionRate(moneyRuleId.value)
      _money = money.value * rate
    }

    if (_money > maxUserScor.value) {
      // score_consumption.value = Math.floor(userScore.value * 10) / 10
      return Math.floor(maxUserScor.value * 10) / 10
    } else {
      // score_consumption.value = Math.floor(_money * 10) / 10
      return Math.floor(_money * 10) / 10
    }
  } else {
    score_consumption.value = 0
    return 0
  }
})

async function getShopInfo() {
  const { data } = await productApi.getShopInfo({
    id: info.shopId,
    detail: true,
    otherColumns: 'moneyRuleDetails'
  })
  const { name, shopMoneyRules, code, user, integralsRuleId, specialStatus } =
    data
  uni.setStorageSync('shopCode', code)
  uni.setStorageSync('shopOwnerShareCode', user.shareCode)
  info.name = name
  console.log('specialStatus=>', specialStatus)
  // 是否白名单用户
  whiteList.value = specialStatus
  //判断是否是花积分和复来券
  if (integralsRuleId == 1) {
    isHjfShop.value = true
    getScore(enumAll.wallet_rule_id_enum.花积分钱包)
    getScore(enumAll.wallet_rule_id_enum.绿色积分钱包)
  }
  if (shopMoneyRules && shopMoneyRules.length > 0) {
    if (moneyRuleId.value) {
      // 判断url携带的moneyRuleId是否还存在（可能规则已删除，但是码或者链接存在滞后）
      const rule = shopMoneyRules.find(
        (item: { moneyRuleId: null }) => item.moneyRuleId == moneyRuleId.value
      )
      if (!rule) {
        info.shopMoneyRules = shopMoneyRules
        moneyRuleId.value = shopMoneyRules[0].moneyRuleId
      }
    } else {
      info.shopMoneyRules = shopMoneyRules
      moneyRuleId.value = shopMoneyRules[0].moneyRuleId
    }
  }
}
watch(accessToken, (newValue, oldValue) => {
  getShopInfo()
})
watch(money, (newValue, oldValue) => {
  console.log(newValue, oldValue, '输入的金额')
  if (newValue) {
    nextTick(() => {
      money.value = newValue.replace(/^(-)*(\d+)\.(\d).*$/, '$1$2.$3')
    })
    if (newValue < 0) {
      uni.showToast({
        icon: 'none',
        title: '金额不能小于0'
      })
      money.value = 0
    } else {
      score_consumption.value = scoreMax.value
      userScore.value =
        Math.floor((maxUserScor.value - scoreMax.value) * 10) / 10
    }
  } else {
    userScore.value = Math.floor(maxUserScor.value * 10) / 10
  }
})

const handleMoney = (val: any) => {
  nextTick(() => {
    if (val < 0) {
      uni.showToast({
        icon: 'none',
        title: '金额不能小于0'
      })
      money.value = 0
    } else {
      score_consumption.value = scoreMax.value
      userScore.value =
        Math.floor((maxUserScor.value - scoreMax.value) * 10) / 10
    }
    val = val.replace(/[^\d.]/g, '') //清除"数字"和"."以外的字符
    val = val.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
    val = val.replace(/^0+\./g, '0.')
    val = val.match(/^0+[1-9]+/) ? (val = val.replace(/^0+/g, '')) : val
    val = val.match(/^\d*(\.?\d{0,1})/g)[0] || ''
    money.value = val
  })
  // let value = e
  // console.log(money.value);

  // this.$nextTick(() => {
  //   let val = e.target.value.toString();
  //   val = val.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
  //   val = val.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
  //   val = val.replace(/^0+\./g, '0.');
  //   val = val.match(/^0+[1-9]+/) ? val = val.replace(/^0+/g, '') : val
  //   val = (val.match(/^\d*(\.?\d{0,2})/g)[0]) || ''

  //   if (val.includes(".")) {
  //     let numDian = val.toString().split(".")[1].length;
  //     if (numDian === 2) {
  //       this.moneyMaxLeng = val.length;
  //     }
  //   } else {
  //     this.moneyMaxLeng = 8;
  //   }
  //   this.writeMoney = val;
  // });
}

function radioGroupChange(e: any) {
  console.log(e)
}
const inptDisabled = ref(false)
const btnColor = ref('2979ff')
onLoad(async (option) => {
  if (option) {
    const { shopId } = option
    info.shopId = shopId
    if (option.moneyRuleId) {
      moneyRuleId.value = option.moneyRuleId
    }
    getShopInfo()
  }
  console.log(userInfo, '用户信息')

  if (!userStore.hasLogin) {
    uni.navigateTo({
      url: '/pages/login/index'
    })
  }
  if (option?.money) {
    money.value = option.money
    inptDisabled.value = true
  }
  if (option?.color) {
    btnColor.value = option.color
  }
})
</script>

<style lang="scss" scoped>
.physicalShopCheck {
  padding: 30rpx;
  text-align: center;
  background: linear-gradient(#fab791 0%, rgba(255, 250, 224, 0) 30%);

  .topTitLe {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;

    .leftTitle {
      text-align: left;
    }
  }

  .shopBox {
    // margin: 0 10rpx;
    padding: 20rpx;
    min-height: 200rpx;
    // border: 2rpx solid #f74e3f;
    background: url('@/static/pay1.png') no-repeat;
    background-size: 100% 100%;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1); // 外部阴影

    .name {
      text-align: center;
      margin-top: 20rpx;
      font-size: 32rpx;
      font-weight: bold;
    }
  }

  .inptBox {
    display: flex;
    justify-content: center;
    align-items: flex-end;
    padding: 20rpx 0;
    border-top: 1px solid #8080802e;
    border-bottom: 1px solid #8080802e;
    position: relative;
    margin-top: 40rpx;
    font-size: 50rpx;

    .unit {
      right: 0;
      top: 36rpx;
      font-size: 28rpx;
      margin-bottom: 10rpx;
    }
  }

  .yt-list-cell {
    display: flex;
    align-items: center;
    padding: 40rpx 0;
    position: relative;

    .cell-tit {
      flex: 1;
      font-size: 26rpx;
      color: #909399;
      text-align: left;

      .red {
        // color: #f92c1d;
        color: #ff6c18;
      }
    }

    &.shape2 {
      display: block;

      .cell-tip {
        display: flex;
        justify-content: space-between;
        margin-top: 20rpx;
        align-items: center;

        .wallet {
          font-size: 28rpx;
          color: #ff6c18;
        }
      }
    }
  }

  .hjfScore {
    margin-top: 10rpx;
    text-align: left;
    color: #909399;
  }

  .radioBox {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 40rpx;

    :deep(.u-radio) {
      justify-content: center;
    }
  }

  .hy-btn {
    margin-top: 50rpx;
  }

  .hy-link {
    margin-top: 10rpx;
    text-align: right;
    color: #909399;
    //下划线
    text-decoration: underline;
  }
}

.inputBox {
  // border: none;
  // border-top: 1rpx solid #e1e1e1;
  // border-bottom: 1rpx solid #e1e1e1;
}
</style>
